﻿using E.Tool;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Area : MonoBehaviour
{
    [Header("基本信息")]
    public Role owner = null;
    public FloatProperty health = new(0, 0, 0);
    public float healthBuff = 0;
    public int level = 1;

    [Header("占领信息")]
    public float captureTime = 5;
    public List<Role> roles = new();
    public Role captureProgressOwner = null;
    public float captureProgress = 0;
    public float captureTimeNow = 0;
    public bool isAddProgress = true;

    public void Init(Role owner, float health, float healthBuff, int level = 1)
    {
        this.owner = owner;
        this.health = new FloatProperty(health, 0, health);
        this.healthBuff = healthBuff;
        this.level = level;
    }

    public void AddCaptureRole(Role role)
    {
        if (roles.Count == 0)
        {
            roles.Add(role);
            captureProgressOwner = role;
            isAddProgress = true;
        }
        else
        {
            roles.Add(role);
        }
    }
    public void RemoveCaptureRole(Role role)
    {
        roles.Remove(role);
        if (roles.Count == 1 && roles[0] != null)
        {
            if (roles[0] == captureProgressOwner)
            {
                isAddProgress = true;
            }
            else
            {
                isAddProgress = false;
            }
        }
    }

    private void Update()
    {
        //占领逻辑
        if (roles.Count == 1 && roles[0] != null)
        {
            //如果不是领主
            if (roles[0] != owner)
            {
                if (isAddProgress)
                {
                    //占领进度更新
                    captureTimeNow += Time.deltaTime;
                    captureProgress = captureTimeNow / captureTime;
                    //如果占领进度已满
                    if (captureTimeNow >= captureTime)
                    {
                        //占领成功
                        owner = roles[0];
                        //重置
                        captureTimeNow = 0;
                        captureProgress = 0;
                        captureProgressOwner = null;

                        //更新颜色
                        GetComponent<Renderer>().material.color = owner.GetComponent<Renderer>().material.color;
                    }
                }
                else
                {
                    //占领进度更新
                    captureTimeNow -= Time.deltaTime;
                    captureProgress = captureTimeNow / captureTime;
                    //如果他人占领进度已清空
                    if (captureTimeNow <= 0)
                    {
                        //开始自己的占领进度
                        isAddProgress = true;
                        captureProgressOwner = roles[0];
                    }

                }
            }

        }
    }

    private void OnValidate()
    {
        transform.localScale = new Vector3(level, level, 0);
    }
}
